package com.yatb.trac.controller.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.CollectionUtils;

import com.yatb.trac.controller.TicketFinderByIdTicket;
import com.yatb.trac.controller.common.loaders.HttpObjectsLoader;
import com.yatb.trac.pojo.Stati;
import com.yatb.trac.pojo.Tickets;
import com.yatb.trac.pojo.wrappers.StatiView;
import com.yatb.trac.pojo.wrappers.UtentiView;
import com.yatb.trac.service.SearchService;
import com.yatb.trac.util.SQLCondition;

public class LoadManageTicketData implements HttpObjectsLoader {

	private SearchService searchService;

	public void load(HttpServletRequest request, HttpServletResponse response) {
		UtentiView utenteLoggato = (UtentiView) request.getSession()
				.getAttribute("loginForm");

		if(request.getParameter("idStato")!=null){
			request.setAttribute("idStato", request.getParameter("idStato"));
		}
		if(request.getParameter("idUtenteAssegnatario")!=null){
			request.setAttribute("idUtenteAssegnatario", request.getParameter("idUtenteAssegnatario"));
		}
		

//		if (request.getSession(false).getAttribute("stati") == null) {
//			StatiView[] stati = getSearchService().findAllStati();
//			request.getSession(false).setAttribute("stati", stati);
//		}

		if (utenteLoggato.getUtenti().getProfilo().getDescrizione()
				.equalsIgnoreCase("DEVELOPER")) {
			if (request.getSession(false).getAttribute("assegnatari") == null) {
				String idTicket = request.getParameter("idTicket");
				SQLCondition sqlCondition = new TicketFinderByIdTicket(idTicket);
				Tickets tickets = getSearchService().find(new Tickets[0],
						sqlCondition, Tickets.class)[0];
				UtentiView[] utentiViews = searchService
						.findUtentiAbilitatiProgettoByProfilo(tickets
								.getIdProgetto().toPlainString(), utenteLoggato
								.getUtenti().getProfilo());
				request.getSession(false).setAttribute("assegnatari", CollectionUtils
						.arrayToList(utentiViews));
			}
		}
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

}
